import PropTypes from '@/utils/PropTypes'
import { defineComponent, ref, h, toRefs } from 'vue'
import { Row, Col, Form, Space, Button } from 'ant-design-vue'
import colorConfig from '@/assets/color.json'
import dayjs from 'dayjs'
import { debounceHandlerFun } from '@/utils/lodash'

type FormParamType = {
  label: string
  name: string
  type: any
  component: any
  width?: string
  placeholder?: string
  fieldNames?: { label: string; value: string }
  options?: any[]
  value?: any
  rules?: {
    required: boolean
    message: string
  }
  children?: FormParamType[]
}
export default defineComponent({
  name: 'formCom',
  props: {
    formParam: PropTypes.array<FormParamType>().def([]),
    formState: PropTypes.object().def({}),
    labelCol: PropTypes.object().def({ span: 7 }),
    wrapperCol: PropTypes.object().def({ span: 16 }),
    loading: PropTypes.bool().def(false),
    footer: PropTypes.bool().def(true),
  },
  emits: ['update:formState', 'update:submit', 'update:loading'],
  setup(props, { slots, emit }) {
    const { formParam, formState, footer, loading } = toRefs(props)
    const formRef = ref()
    const resetForm = () => {
      formRef.value?.resetFields()
      formParam.value.forEach((v: any) => {
        if (v.value) {
          formState.value[v.name] = ''
          v.value.forEach((k: any) => (formState.value[k] = ''))
        }
      })
    }
    const onFinish = (values: any) => {
      emit('update:loading', true)
      emit('update:submit')
    }
    const onFinishFailed = (errorInfo: any) => {
      console.log('Failed:', errorInfo)
    }
    const getValue = (value: any) => {
      const arr = []
      if (value && value.length) {
        formState.value[value[0]] && arr.push(dayjs(formState.value[value[0]]))
        formState.value[value[1]] && arr.push(dayjs(formState.value[value[1]]))
      }
      return arr
    }
    return () => (
      <div>
        <Form
          layout="inline"
          name="formState"
          ref={formRef}
          model={formState.value}
          class="form-table"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <>
            {formParam.value.map((v: any, index) => (
              <Form.Item label={v.label} name={v.name} rules={v.rules}>
                {h(
                  v.component, // 组件类型
                  {
                    ...v,
                    style: { width: v.width },
                    value: formState.value[v.name],
                    onInput: (e: any) => {
                      if (v.name == 'RangePicker') return
                      formState.value[v.name] = e.target.value
                    },
                    onChange: (e: any) => {
                      if (v.type == 'Select') {
                        formState.value[v.name] = e
                        return
                      }
                      if (v.type == 'DatePicker') {
                        formState.value[v.value[0]] =
                          e && dayjs(e).format(v.formate)
                        return
                      }
                      if (v.type == 'RangePicker') {
                        debounceHandlerFun(() => {
                          formState.value[v.value[0]] = dayjs(e[0]).format(
                            v.formate,
                          )
                          formState.value[v.value[1]] = dayjs(e[1]).format(
                            v.formate,
                          )
                        }, v.delay)
                      }
                    },
                  },
                )}
                {v.children &&
                  v.children.map((item: any) =>
                    h(
                      item.component, // 组件类型
                      {
                        style: { width: item.width, ...item.style },
                        name: item.name,
                        options: item.options,
                        placeholder: item.placeholder && item.placeholder,
                        value: formState.value[item.name],
                        onInput: (e: any) => {
                          formState.value[item.name] = e.target.value
                        },
                      },
                    ),
                  )}
              </Form.Item>
            ))}
            <Col>
              {slots.default ? (
                slots.default()
              ) : (
                <>
                  {footer.value && (
                    <Form.Item>
                      <Space>
                        <Button
                          type="primary"
                          html-type="submit"
                          loading={loading.value}
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                          }}
                        >
                          查询
                        </Button>
                        <Button
                          style={{
                            backgroundColor: colorConfig.color.reset,
                            color: '#fff',
                            display: 'flex',
                            alignItems: 'center',
                          }}
                          onClick={resetForm}
                        >
                          重置
                        </Button>
                      </Space>
                    </Form.Item>
                  )}
                </>
              )}
            </Col>
          </>
        </Form>
      </div>
    )
  },
})
